package net.adetech.dcweb.core.common.service.impl;

import net.adetech.utils.condition.ConditionEntity;
import net.adetech.utils.condition.ConditionTools;
import net.adetech.utils.condition.SQLEntity;
import net.adetech.utils.spring.PageBean;
import net.adetech.dcweb.core.common.service.ICommonCodeService;
import net.adetech.dcweb.core.common.entity.CommonCode;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by sunfeihu on 2016/10/20.
 */
@Service
public class CommonCodeServiceImpl implements ICommonCodeService {

    private final Logger logger = LoggerFactory.getLogger(CommonCodeServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public CommonCode save(CommonCode entity) {
        final String sql = " insert into common_code (uuid,add_user,add_date,add_ip,add_info,update_user,update_ip,update_date,update_info,is_delete,code_name,code_type,code_definition,code_remark) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final CommonCode finalEntity = entity;
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1, finalEntity.getUuid());
                ps.setObject(2, finalEntity.getAddUser());
                if (null != finalEntity.getAddDate()) {
                    ps.setObject(3, new Timestamp(finalEntity.getAddDate().getTime()));
                } else {
                    ps.setObject(3, null);
                }
                ps.setObject(4, finalEntity.getAddIp());
                ps.setObject(5, finalEntity.getAddInfo());
                ps.setObject(6, finalEntity.getUpdateUser());
                ps.setObject(7, finalEntity.getUpdateIp());
                if (null != finalEntity.getUpdateDate()) {
                    ps.setObject(8, new Timestamp(finalEntity.getUpdateDate().getTime()));
                } else {
                    ps.setObject(8, null);
                }
                ps.setObject(9, finalEntity.getUpdateInfo());
                ps.setObject(10, finalEntity.getIsDelete());
                ps.setObject(11, finalEntity.getCodeName());
                ps.setObject(12, finalEntity.getCodeType());
                ps.setObject(13, finalEntity.getCodeDefinition());
                ps.setObject(14, finalEntity.getCodeRemark());
                return ps;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        return this.find(id);
    }

    @Override
    public int delete(Long id) {
        final String sql = " update common_code set is_delete = 1 where id = ? ";
        return jdbcTemplate.update(sql, new Object[]{
                id
        });
    }

    @Override
    public int update(CommonCode entity) {
        final String sql = " update common_code set add_info=?,update_info=?,code_name=?,code_type=?,code_definition=?,code_remark=? where id = ?";
        return jdbcTemplate.update(sql, new Object[]{
                entity.getAddInfo(),
                entity.getUpdateInfo(),
                entity.getCodeName(),
                entity.getCodeType(),
                entity.getCodeDefinition(),
                entity.getCodeRemark(),
                entity.getId()
        });
    }

    @Override
    public CommonCode find(Long id) {
        final String sql = " select * from common_code where id = ? and is_delete = 0 ";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CommonCodeRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public CommonCode findByCodeName(String codeName) {
        final String sql = " select * from common_code where code_name = ?  ";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{codeName}, new CommonCodeRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<CommonCode> findByCodeNamePrefix(String prefix) {


        final String sql = " select * from common_code where code_name like ?  ";
        try {
            return jdbcTemplate.query(sql, new Object[]{prefix+"%"}, new CommonCodeRowerMapper());
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void save(List<CommonCode> list) {
        if (null != list && list.size() > 0) {
            final String sql = " insert into common_code (uuid,add_user,add_date,add_ip,add_info,update_user,update_ip,update_date,update_info,is_delete,code_name,code_type,code_definition,code_remark) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            List
                    <Object[]> params = new ArrayList
                    <Object[]>();
            Object[] objArr = null;
            CommonCode entity = null;
            for (int i = 0; i < list.size(); i++) {
                entity = list.get(i);
                objArr = new Object[14];
                objArr[0] = entity.getUuid();
                objArr[1] = entity.getAddUser();
                objArr[2] = entity.getAddDate();
                objArr[3] = entity.getAddIp();
                objArr[4] = entity.getAddInfo();
                objArr[5] = entity.getUpdateUser();
                objArr[6] = entity.getUpdateIp();
                objArr[7] = entity.getUpdateDate();
                objArr[8] = entity.getUpdateInfo();
                objArr[9] = entity.getIsDelete();
                objArr[10] = entity.getCodeName();
                objArr[11] = entity.getCodeType();
                objArr[12] = entity.getCodeDefinition();
                objArr[13] = entity.getCodeRemark();
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public void delete(List
                               <Long> ids) {
        if (null != ids && ids.size() > 0) {
            final String sql = " update common_code set is_delete = 1 where id = ? ";
            List
                    <Object
                            []> params = new ArrayList
                    <Object
                            []>();
            Object[] objArr = null;
            for (int i = 0; i < ids.size(); i++) {
                objArr = new Object[1];
                objArr[0] = ids.get(i);
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public void update(List<CommonCode> list) {
        if (null != list && list.size() > 0) {
            final String sql = " update common_code set add_info=?,update_info=?,code_name=?,code_type=?,code_definition=?,code_remark=? where id = ?";
            List
                    <Object
                            []> params = new ArrayList
                    <Object
                            []>();
            Object[] objArr = null;
            CommonCode entity = null;
            for (int i = 0; i < list.size(); i++) {
                entity = list.get(i);
                objArr = new Object[6];
                objArr[0] = entity.getAddInfo();
                objArr[1] = entity.getUpdateInfo();
                objArr[2] = entity.getCodeName();
                objArr[3] = entity.getCodeType();
                objArr[4] = entity.getCodeDefinition();
                objArr[5] = entity.getCodeRemark();
                objArr[6] = entity.getId();
                params.add(objArr);
            }
            jdbcTemplate.batchUpdate(sql, params);
        }
    }

    @Override
    public PageBean<CommonCode> page(int nowPage, int pageSize, ConditionEntity conditionEntity) {
        SQLEntity sqlEntity = ConditionTools.conditionEntities2SQL(conditionEntity);
        final String sql = " select * from common_code where 1 = 1 and is_delete = 0 " + sqlEntity.getSql() + " order by " + sqlEntity.getOrder();
        return new PageBean<CommonCode>(sql, sqlEntity.getParams(), nowPage, pageSize,
                new CommonCodeRowerMapper(), jdbcTemplate);
    }
}


class CommonCodeRowerMapper implements RowMapper<CommonCode> {
    @Override
    public CommonCode mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Set
                <String> fieldSet = new HashSet
                <String>();
        for (int i = 1; i <= columnCount; i++) {
            fieldSet.add(rsmd.getColumnLabel(i));
        }
        CommonCode entity = new CommonCode();
        if (fieldSet.contains("add_date") && null !=
                rs.getObject("add_date")) {
            entity.setAddDate(new
                    java.util.Date(rs.getTimestamp("add_date").getTime()));
        }
        if (fieldSet.contains("code_remark") && null !=
                rs.getObject("code_remark")) {
            entity.setCodeRemark(rs.getString
                    ("code_remark"));
        }
        if (fieldSet.contains("update_info") && null !=
                rs.getObject("update_info")) {
            entity.setUpdateInfo(rs.getString
                    ("update_info"));
        }
        if (fieldSet.contains("update_ip") && null !=
                rs.getObject("update_ip")) {
            entity.setUpdateIp(rs.getString
                    ("update_ip"));
        }
        if (fieldSet.contains("uuid") && null !=
                rs.getObject("uuid")) {
            entity.setUuid(rs.getString
                    ("uuid"));
        }
        if (fieldSet.contains("code_name") && null !=
                rs.getObject("code_name")) {
            entity.setCodeName(rs.getString
                    ("code_name"));
        }
        if (fieldSet.contains("update_date") && null !=
                rs.getObject("update_date")) {
            entity.setUpdateDate(new
                    java.util.Date(rs.getTimestamp("update_date").getTime()));
        }
        if (fieldSet.contains("is_delete") && null !=
                rs.getObject("is_delete")) {
            entity.setIsDelete(rs.getBoolean
                    ("is_delete"));
        }
        if (fieldSet.contains("add_ip") && null !=
                rs.getObject("add_ip")) {
            entity.setAddIp(rs.getString
                    ("add_ip"));
        }
        if (fieldSet.contains("update_user") && null !=
                rs.getObject("update_user")) {
            entity.setUpdateUser(rs.getString
                    ("update_user"));
        }
        if (fieldSet.contains("code_definition") && null !=
                rs.getObject("code_definition")) {
            entity.setCodeDefinition(rs.getString
                    ("code_definition"));
        }
        if (fieldSet.contains("id") && null !=
                rs.getObject("id")) {
            entity.setId(rs.getLong
                    ("id"));
        }
        if (fieldSet.contains("add_info") && null !=
                rs.getObject("add_info")) {
            entity.setAddInfo(rs.getString
                    ("add_info"));
        }
        if (fieldSet.contains("add_user") && null !=
                rs.getObject("add_user")) {
            entity.setAddUser(rs.getString
                    ("add_user"));
        }
        if (fieldSet.contains("code_type") && null !=
                rs.getObject("code_type")) {
            entity.setCodeType(rs.getString
                    ("code_type"));
        }
        return entity;
    }
}